<?php
namespace Admin\Controller;
use Think\Controller;

class CalcController extends Controller {
   
    /**
    * 检测是否停驶
    * 
    * @param mixed $firenum
    * @param mixed $stopnum
    * @param mixed $gps_start_mileage
    * @param mixed $gps_end_mileage
    * @param mixed $start_mileage
    * @param mixed $end_mileage
    * @param mixed $run_time
    */
    protected function testIsStop($firenum,$stopnum,$gps_start_mileage,$gps_end_mileage,$start_mileage,$end_mileage,$run_time){
        if($firenum>0) { //有点火
            if($run_time>120) return false; //发动机启动后运行超过2分钟
            if(($end_mileage-$start_mileage)>2) return false;//行驶里程超过2km
            if(($gps_end_mileage-$gps_start_mileage)>2) return false; //gps里程超过2km
            return true;
        }else{
            return true;
        }
    }
    
    /**
    * 统计按天的车辆行驶记录
    * 
    * @param mixed $start
    * @param mixed $end
    */
    public function calc($start='',$end=''){
        set_time_limit(0); //设置无限制执行时间
        $ip = get_client_ip();
        if($ip!='127.0.0.1'){
            echo 'error!';
            return;
        }
        //$start = '2015-07-20';
        //$end = '2015-07-26';
        $now = new \DateTime();
        $yesterday = $now->sub(new \DateInterval('P1D'));
        if(empty($start)){
            $start = $yesterday->format('Y-m-d');
        }
        $start = new \DateTime($start);
        if(empty($end)){
            $end = $yesterday->format('Y-m-d');
        }
        $end = new \DateTime($end);
        
        //确保时间在昨天之前,不允许运算今天的
        if($start->getTimestamp()>$yesterday->getTimestamp()){
            $start = $yesterday;
        }
        if($end->getTimestamp()>$yesterday->getTimestamp()){
            $end = $yesterday;
        }
        
        $modelDayLog = M('ObdDayLog');
        $modelObd = M('Obd');
        $modelOrder = M('Order');
        $modelOrderAmtLog = M('OrderAmtLog');
        $nCount = 0;
        for($day = $start; $day->getTimestamp() <= $end->getTimestamp(); $day = $day->add(new \DateInterval('P1D'))){
            $dateStr = $day->format('Ymd');
            $modelLog = M("Log_$dateStr",'zb_hp908_report_','OBD_DATACONFIG');
            $modelBase = M("Base_$dateStr",'zb_hp908_report_','OBD_DATACONFIG');
            $modelCheck = M("Obdcheck_$dateStr",'zb_hp908_report_','OBD_DATACONFIG');
            $modelErr = M("Obderr_$dateStr",'zb_hp908_report_','OBD_DATACONFIG');
            $modelVal = M("Obdval_$dateStr",'zb_hp908_report_','OBD_DATACONFIG');

            $resLog = $modelLog->order('logid')->select();
            $retDayLog = array();
            foreach($resLog as $rowLog){
                $obdid = $rowLog['obdid'];
                if(!isset($retDayLog[$obdid])){
                    $retDayLog[$obdid] = array(
                        'firenum' => 0,
                        'stopnum' => 0,
                        'gps_start_mileage' => null,
                        'gps_end_mileage' => null,
                        'start_mileage' => null,
                        'end_mileage' => null,
                        'run_time' => 0,
                        'last_acc' => null,
                        'run_time_once' => 0,
                        'last_activetime' => null,
                    );
                }
                $retDayLog[$obdid]['last_activetime'] = $rowLog['posttime'];
                $map['logid'] = $rowLog['logid'];
                $resBase = $modelBase->where($map)->find();
                if($resBase){
                    if($resBase['alarm0c']!=$retDayLog[$obdid]['last_acc']){
                        if($resBase['alarm0c']==1){//ACC OFF
                            $retDayLog[$obdid]['stopnum'] ++;
                            
                            //计时累加
                            $retDayLog[$obdid]['run_time'] += $retDayLog[$obdid]['run_time_once'];
                            $retDayLog[$obdid]['run_time_once'] = 0;
                        }else{
                            $retDayLog[$obdid]['firenum'] ++;
                        }
                        $retDayLog[$obdid]['last_acc'] = $resBase['alarm0c'];
                    }
                    if($resBase['mileage_flag']==82){//有GPS里程数据
                        if(is_null($retDayLog[$obdid]['gps_start_mileage'])){
                            $retDayLog[$obdid]['gps_start_mileage'] = $resBase['mileage'];
                        }
                        $retDayLog[$obdid]['gps_end_mileage'] = $resBase['mileage'];
                    }
                }
                $resVal = $modelVal->where($map)->find();
                if($resVal){
                    if(!is_null($resVal['v1f'])){ //发动机运行时间
                        $retDayLog[$obdid]['run_time_once'] = $resVal['v1f'];
                    }
                    if(!is_null($resVal['v8a'])){//里程数据
                        if(is_null($retDayLog[$obdid]['start_mileage'])){
                            $retDayLog[$obdid]['start_mileage'] = $resVal['v8a'];
                        }
                        $retDayLog[$obdid]['end_mileage'] = $resVal['v8a'];
                    }
                }
            }
            
            //统计好的数据写入数据库
            $pdate = $day->format('Y-m-d');
            foreach($retDayLog as $obdid => $data){
                if(is_null($data['start_mileage'])) $data['start_mileage'] = 0;
                if(is_null($data['end_mileage'])) $data['end_mileage'] = 0;
                if(is_null($data['gps_start_mileage'])) $data['gps_start_mileage'] = 0;
                if(is_null($data['gps_end_mileage'])) $data['gps_end_mileage'] = 0;
                
                //判断是否行驶过
                if($this->testIsStop($data['firenum'],$data['stopnum'],
                                    $data['gps_start_mileage'],$data['gps_end_mileage'],
                                    $data['start_mileage'],$data['end_mileage'],$data['run_time'])){
                    $car_status = 0;
                }else{
                    $car_status = 1;
                }
                
                $sql = "insert into __TABLE__ (obdid,pdate,firenum,stopnum,gps_start_mileage,gps_end_mileage,start_mileage,end_mileage,run_time,car_status) 
                    values($obdid,'$pdate',{$data['firenum']},{$data['stopnum']},{$data['gps_start_mileage']},{$data['gps_end_mileage']},
                    {$data['start_mileage']},{$data['end_mileage']},{$data['run_time']},{$car_status}) ON DUPLICATE KEY UPDATE firenum={$data['firenum']},
                    stopnum={$data['stopnum']},gps_start_mileage={$data['gps_start_mileage']},gps_end_mileage={$data['gps_end_mileage']},
                    start_mileage={$data['start_mileage']},end_mileage={$data['end_mileage']},run_time={$data['run_time']},car_status={$car_status}";
                $modelDayLog->execute($sql);
                
                $sql = "insert into __TABLE__ (obdid,last_active_date) values($obdid,'{$data['last_activetime']}') ON DUPLICATE KEY UPDATE last_active_date='{$data['last_activetime']}'";
                $modelObd->execute($sql);
                
                $nCount++;
            }
            
            //计算当天奖励
            unset($map);
            $map['status'] = 2;  //仅当订单有交钱成功，出单成功有效
            $resOrder = $modelOrder->where($map)->select();
            foreach($resOrder as $order){
                if($order['start_date']>$pdate){ //在之前，不处理
                    
                }else if($order['end_date']>=$pdate){//在有效期内
                    //增加可用账户金额
                    $n_amt = $order['n_amt'];
                    $n_frozen_amt = $order['n_frozen_amt'];
                    $run_num = $order['run_num']; //行驶天数
                    $stop_num = $order['stop_num']; //停驶天数

                    M()->startTrans();                    
                    unset($where);
                    $where['order_id'] = $order['order_id'];
                    $where['pdate'] = $pdate;
                    $where['isfrozen'] = 0;
                    $where['ptype'] = 1;
                    $resLast = $modelOrderAmtLog->where($where)->order('pid desc')->find();
                    if($resLast){//如果已经计算过了的话，要先减去计算所得
                        $Amt = $resLast['chgval'];
                        $where['initval'] = $n_amt;
                        $where['chgval'] = -$Amt;
                        $where['endval'] = $n_amt - $Amt;
                        $where['memo'] = '重新计算，金额调整';
                        $modelOrderAmtLog->add($where);
                        $n_amt -= $Amt; 
                        
                        $run_num --; //行驶天数减回去   
                    }
                    $where['initval'] = $n_amt;
                    $where['chgval'] = $order['day_amt'];
                    $where['endval'] = $n_amt + $order['day_amt'];
                    $where['memo'] = '每天基本奖励';
                    $modelOrderAmtLog->add($where);
                    
                    if(!empty($order['obdid'])){
                        unset($map);
                        $map['obdid'] = $order['obdid'];
                        $map['pdate'] = $pdate;
                        $resDayLog = $modelDayLog->where($map)->find();
                        if($resDayLog && $resDayLog['car_status']=='0'){//有记录并且停驶
                            //TODO:这里有BUG!!!!!!!!!
                            unset($where);
                            $where['order_id'] = $order['order_id'];
                            $where['pdate'] = $pdate;
                            $where['isfrozen'] = 1;
                            $where['ptype'] = 1;
                            $resLast = $modelOrderAmtLog->where($where)->order('pid desc')->find();
                            if($resLast){//如果已经计算过了的话，要先减去计算所得
                                $Amt = $resLast['chgval'];
                                $where['initval'] = $n_frozen_amt;
                                $where['chgval'] = -$Amt;
                                $where['endval'] = $n_frozen_amt - $Amt;
                                $where['memo'] = '重新计算，金额调整';
                                $modelOrderAmtLog->add($where);
                                $n_frozen_amt -= $Amt;
                                
                                $stop_num --;
                            }

                            $stop_num ++;
                            
                            $where['initval'] = $n_frozen_amt;
                            $where['chgval'] = $order['day_frozen_amt'];
                            $where['endval'] = $n_frozen_amt + $order['day_frozen_amt'];
                            $where['memo'] = '停驶环保奖励';
                            $modelOrderAmtLog->add($where);
                        }
                    }else{
                        $run_num ++;
                    }
                    
                    unset($data);
                    $data['n_amt'] = $n_amt;
                    $data['n_frozen_amt'] = $n_frozen_amt;
                    $data['run_num'] = $run_num;
                    $data['stop_num'] = $stop_num;
                    $modelOrder->where("order_id=".$order['order_id'])->save($data);
                    M()->commit(); 
                }else{//如果日期超过订单的结束日期，需要修改订单状态
                    unset($data);
                    $data['status'] = 3; //订单已经结束
                    $modelOrder->where('order_id='.$order['order_id'])->save($data);
                    //TODO:订单冻结金额转可用余额
                }
            }

            /*
            //计算基本奖励
            $modelAccount = M('UserAccount');
            $modelAccountLog = M('UserAccountLog');
            unset($map);
            $map['status'] = 1;
            $resAccount = $modelAccount->where($map)->select();
            foreach($resAccount as $rowAccount){
                if($rowAccount['start_date']<=$pdate && $rowAccount['end_date']>=$pdate){//在有效期内
                    if($rowAccount['account_type']==1){ //基本奖励
                        M()->startTrans();
                        unset($dataLog);
                        $dataLog['account_id'] = $rowAccount['account_id'];
                        $dataLog['pdate'] = $pdate;
                        $dataLog['ptype'] = 1;//表示进账
                        $dataLog['initval'] = $rowAccount['balance'];
                        $dataLog['chagval'] = $rowAccount['day_fee'];
                        $dataLog['endval'] = $rowAccount['balance']+$rowAccount['day_fee'];
                        $dataLog['memo'] = '基本奖励';
                        $modelAccountLog->add($dataLog);
                        
                        unset($dataAccount);
                        $dataAccount['balance'] = $rowAccount['balance']+$rowAccount['day_fee'];
                        $modelAccount->where('account_id='.$rowAccount['account_id'])->save($dataAccount);
                        M()->commit();
                    }else if($rowAccount['account_type']==2){//环保奖励
                        $car = $modelCarDayLog->where('car_id='.$rowAccount['car_id'])->find();
                        if($car){
                            if($car['status']==0){
                                M()->startTrans();
                                unset($dataLog);
                                $dataLog['account_id'] = $rowAccount['account_id'];
                                $dataLog['pdate'] = $pdate;
                                $dataLog['ptype'] = 1;//表示进账
                                $dataLog['initval'] = $rowAccount['balance'];
                                $dataLog['chagval'] = $rowAccount['day_fee'];
                                $dataLog['endval'] = $rowAccount['balance']+$rowAccount['day_fee'];
                                $dataLog['memo'] = '环保奖励';
                                $modelAccountLog->add($dataLog);
                                
                                unset($dataAccount);
                                $dataAccount['balance'] = $rowAccount['balance']+$rowAccount['day_fee'];
                                $modelAccount->where('account_id='.$rowAccount['account_id'])->save($dataAccount);
                                M()->commit();
                            }
                        }
                    }
                }else{
                    //更改账户状态
                    unset($map);
                    $map['account_id'] = $rowAccount['account_id'];
                    $dataAccount['status'] = 0;
                    $modelAccount->where($map)->save($dataAccount);
                }
            } */   
        }
        $this->success("共更新产生{$nCount}条数据。");
    }   
}
